package virtorina.server.servlet;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.google.appengine.repackaged.org.json.JSONException;
import com.google.appengine.repackaged.org.json.JSONObject;

import virtorina.server.Base;
import virtorina.server.PMF;
import virtorina.server.domain.Label;
import virtorina.server.domain.Question;
import virtorina.server.domain.QuestionLabel;
import virtorina.server.domain.User;

public class auth extends HttpServlet {

	private static final long serialVersionUID = 1L;
	HttpServletRequest request;
	HttpServletResponse response;

	public void doPost(HttpServletRequest request, HttpServletResponse response) {
		this.request = request;
		this.response = response;
		String token = request.getParameter("token");
		if (token != null) {
			try {
				String str = getJsonStr(token);
				JSONObject Answ = new JSONObject(str);
				setUser(Answ);
			} catch (JSONException e) {
				e.printStackTrace();
			}
		} else {
			try {
				response.sendRedirect("http://instant-quiz.appspot.com");
				// response.sendRedirect("http://127.0.0.1:8888");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	private static final Logger log = Logger.getLogger(auth.class.getName());

	public void doGet(HttpServletRequest request, HttpServletResponse response) {
		if (request.getParameter("logout") != null) {
			HttpSession session = request.getSession();
			Long id = (Long) session.getAttribute("user");
			int RoomID;
			try {
				RoomID = (Integer) session.getAttribute("RoomID");
			} catch (NullPointerException e) {
				try {
					response.sendRedirect("http://instant-quiz.appspot.com/rooms.html");
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				return;
			}
			Base.getRoom(RoomID).leave(id);
			session.setAttribute("user", null);
			session.setAttribute("RoomID", null);
		} else if (request.getParameter("tmp") != null) {

		} else if (request.getParameter("tmpDEV") != null) {

		}
		try {
			response.sendRedirect("http://instant-quiz.appspot.com/rooms.html");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// response.sendRedirect("http://127.0.0.1:8888");
	}

	private void setUser(JSONObject Answ) {
		try {
			response.setContentType("text/plain");
			String UserProfile = Answ.getString("identity");
			User user = User.getByProfile(UserProfile);
			HttpSession session = request.getSession();
			Long id = (Long) session.getAttribute("user");
			Integer RoomID = (Integer) session.getAttribute("RoomID");
			if (RoomID != null) {
				Base.getRoom(RoomID).leave(id);
			}
			session.setAttribute("user", null);
			session.setAttribute("RoomID", null);
			if (user == null) {
				user = User.addUser(UserProfile);
				session.setAttribute("user", user.getUserID());
			} else {
				session.setAttribute("user", user.getUserID());
			}
			if (RoomID != null) {
				response.sendRedirect("http://instant-quiz.appspot.com/room.html?id="
						+ RoomID);
			} else {
				response.sendRedirect("http://instant-quiz.appspot.com/rooms.html");
			}
			// response.sendRedirect("http://127.0.0.1:8888");
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private String getJsonStr(String token) {
		try {
			URL url = new URL("http://loginza.ru/api/authinfo?token=" + token);
			URLConnection con = url.openConnection();
			Reader r = new InputStreamReader(con.getInputStream());

			StringBuilder buf = new StringBuilder();
			while (true) {
				int ch = r.read();
				if (ch < 0)
					break;
				buf.append((char) ch);
			}
			return buf.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
